package com.plm.htmlfiledownload.home;

import com.plm.htmlfiledownload.common.PDFUtil;
import com.plm.htmlfiledownload.common.Util;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName: HTMLFileDownLoadController
 * @Description: 页面文件下载
 * @Author pengliming
 * @Date 14:14 2019/6/12
 */
@RequestMapping("/")
@Controller
public class HTMLFileDownLoadController {

    @RequestMapping("/")
    public String goHome() {
        return "home";
    }

    @RequestMapping("/upload")
    public String upload(HttpServletRequest request, HttpServletResponse response) {
        OutputStream bos = null;
        try {
            String uuid = UUID.randomUUID().toString();
            //最终文件路径
            String fileLastPath = "C:\\Users\\花爸爸\\Desktop\\pdf\\"+uuid+".pdf";
            //1 准备要填充的数据
            Map paraMap = new HashMap();
            paraMap.put("XM", request.getParameter("XM"));
            paraMap.put("XB", request.getParameter("XB"));
            paraMap.put("MZ", request.getParameter("MZ"));
            paraMap.put("CSRQ", request.getParameter("CSRQ"));
            paraMap.put("SFZBH", request.getParameter("SFZBH"));
            PDFUtil.pdfCreate(fileLastPath,paraMap);
            File file = new File(fileLastPath);
            byte[] by = Util.toByteArray(file);
            //byte[] by = sftpBase.downloadWithBytes(remoteFilePath, fileName); //获取文件流
            if (!Util.isNullOrEmpty(by)) {
                response.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode("pdf.pdf".trim(), "UTF-8") + "\"");
                bos = response.getOutputStream();
                bos.write(by);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.flush();
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

}
